package main.java.com.negromotad.model;

import java.util.List;

import main.java.com.negromotad.configuration.TMGeneticAlgorithmConfigurator;
import main.java.com.negromotad.genetics.TMChromosome;
import main.java.com.negromotad.genetics.TMGeneticAlgorithm;
import main.java.com.negromotad.genetics.rules.TMRule;
import main.java.com.negromotad.parser.TMDataLoader;

import org.jgap.InvalidConfigurationException;

public class TMRun implements Runnable, TMAlgorithmObserver {

	private TMDataLoader tmDataLoader;
	private TMGeneticAlgorithmConfigurator tmAlgorithmConfigurator;
	private List<TMRule> rules;
	private TMAlgorithmObserver observer;
	private int expectative;
	private int target;

	public void init(TMDataLoader dataLoader,
			TMGeneticAlgorithmConfigurator algorithmConfigurator,
			List<TMRule> theRules, int theExpectative, int theTarget) {
		this.tmDataLoader = dataLoader;
		this.tmAlgorithmConfigurator = algorithmConfigurator;
		this.rules = theRules;
		this.expectative = theExpectative;
		this.target = theTarget;
	}

	@Override
	public void run() {
		TMGeneticAlgorithm tam = new TMGeneticAlgorithm(tmDataLoader,
				tmAlgorithmConfigurator);
		tam.setObserver(this);
		try {
			TMChromosome bestSolutionSoFar = tam.calculateBestDistribution(
					rules, target, expectative);
		} catch (InvalidConfigurationException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(TMChromosome chromosome, int evolution, boolean goOn, boolean maxFailure) {
		if (observer != null)
			observer.update(chromosome, evolution, goOn, maxFailure);
	}

	public void setObserver(TMAlgorithmObserver observer) {
		this.observer = observer;
	}

	public int getExpectative() {
		return expectative;
	}

	public int getTarget() {
		return target;
	}

}
